﻿using SimplyCleverMiddleTier;
using System.Linq;
using System.Web.Mvc;

namespace MvcSimplyCleverPart3
{
    public static class ViewHelper
    {
        public static SelectList GetCountries(string countryCode)
        {
            var metadataCountries = CountryProvider.GetCountries();
            SelectList countries = new SelectList(metadataCountries, "Code", "Name");

            return countries;
        }

        public static SelectList GetStates(string countryCode, string stateCode)
        {
            var metadataCountries = CountryProvider.GetCountries();

            var metadataCountry = metadataCountries.FirstOrDefault(cm => cm.Code.Equals(countryCode));

            if (metadataCountry == null)
                return null;

            if (string.IsNullOrEmpty(stateCode))
                stateCode = metadataCountry.States.First().Key;

            SelectList states = new SelectList(metadataCountry.States, "Key", "Value", stateCode);

            return states;
        }

        public static string GetCountryName(string countryCode)
        {
            if(string.IsNullOrEmpty(countryCode))
                return string.Empty;

            var metadataCountries = CountryProvider.GetCountries();
            var metadataCountry = metadataCountries.FirstOrDefault(cm => cm.Code.Equals(countryCode));

            if (metadataCountry == null)
                return string.Empty;
            
            return metadataCountry.Name;
        }
    }
}